package com.example.controller;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.example.dto.TestDto;
import com.sinosoft.common.encrypt.annotation.ApiEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;



@RestController
@RequestMapping("/api")
@Slf4j
public class DemoController {

    /**
     * 使用@ApiEncrypt注解的测试方法
     * 该方法会接收加密的请求体，解密后输出明文，然后返回加密的响应
     */
    @PostMapping("/test")
    @ApiEncrypt(response = true)
    public Map<String, Object> testEncrypt(@RequestBody String decryptedBody) {
        // 这里会接收到解密后的明文
        System.out.println("=== 服务器接收到解密后的明文 ===");
        System.out.println("解密后的明文: " + decryptedBody);
        System.out.println("==================================");
        
        // 构建响应数据
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "加密解密测试成功");
        response.put("data", "这是服务器返回的明文数据");
        response.put("timestamp", System.currentTimeMillis());
        response.put("receivedData", decryptedBody);
        response.put("serverInfo", "SpringBoot加密解密演示服务器");
        
        System.out.println("=== 服务器准备返回的明文数据 ===");
        System.out.println("响应数据: " + response);
        System.out.println("==================================");
        
        return response;
    }

    /**
     * 简单的健康检查接口
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("message", "服务正常运行");
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
    
    /**
     * 测试接口 - 不使用加密
     */
    @PostMapping("/test-plain")
    public Map<String, Object> testPlain(@RequestBody String body) {
        System.out.println("=== 接收到明文请求 ===");
        System.out.println("请求体: " + body);
        System.out.println("=====================");
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "明文请求测试成功");
        response.put("receivedData", body);
        response.put("timestamp", System.currentTimeMillis());
        
        return response;
    }

    /**
     * 测试手动加密解密
     */
    @PostMapping("/testshoudong")
    public void testShoudong(String body) {
        System.out.println("=== 接收到明文请求 ===");
        System.out.println("请求体: " + body);
        System.out.println("=====================");
        System.out.println("=== 开始手动加密 ===");
        String s = EncryptUtils.sm4Encrypt(body, "6ed645ef0e1abea1bf1e4e935ff04f9e");
        System.out.println("加密后: " + s);
        System.out.println("=====================");
        System.out.println("=== 测试手动解密 ===");
        String s1 = EncryptUtils.sm4Decrypt(s, "6ed645ef0e1abea1bf1e4e935ff04f9e");
        System.out.println("解密后: " + s1);
    }
    //测试明文 加密后 ugHs7gqeP/iQ3WDdEfQeUg==

    @Value("${api-decrypt.sm2-public-key}")
    public String sm2PublicKey;
    @Value("${api-decrypt.sm2-private-key}")
    public String sm2PrivateKey;

    //BGmTOVXZxY3AoSW2M91sBN73hsrtixRybJ1pcJc7YVfM5yAyuKHxsQQ3NHaQ8Tf1rPp1DZ1c1L8Z1ouqUTAsAM6/Wtk8xrqDdK8N/4CILlj/T53FOgS+RThdyiNLo7bStSb8FfI/+r9bSm6D1XtVWr4=


    /**
     * 测试密钥格式和匹配性
     */
    @GetMapping("/testKeys")
    public Map<String, String> testKeys() {
        Map<String, String> result = new HashMap<>();
        try {
            // 测试当前配置的密钥
            SM2 sm2 = new SM2(sm2PrivateKey, sm2PublicKey);
            result.put("status", "success");
            result.put("message", "密钥格式正确");
            result.put("privateKeyLength", String.valueOf(sm2PrivateKey.length()));
            result.put("publicKeyLength", String.valueOf(sm2PublicKey.length()));

            // 测试加密解密匹配性
            String testText = "test123";
            String encrypted = sm2.encryptBase64(testText, KeyType.PublicKey);
            String decrypted = sm2.decryptStr(encrypted, KeyType.PrivateKey);

            if (testText.equals(decrypted)) {
                result.put("match", "true");
                result.put("message", "密钥对匹配正确");
            } else {
                result.put("match", "false");
                result.put("message", "密钥对不匹配");
            }
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "密钥格式错误: " + e.getMessage());
            result.put("privateKeyLength", String.valueOf(sm2PrivateKey.length()));
            result.put("publicKeyLength", String.valueOf(sm2PublicKey.length()));
        }
        return result;
    }

    /**
     * 验证Base64格式
     */
    private boolean isValidBase64(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        try {
            java.util.Base64.getDecoder().decode(str);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * 调试Base64格式
     */
    @PostMapping("/debugBase64")
    public Map<String, Object> debugBase64(String ciphertext) {
        Map<String, Object> result = new HashMap<>();
        
        result.put("originalLength", ciphertext.length());
        result.put("originalText", ciphertext);
        
        // 检查每个字符
        StringBuilder charAnalysis = new StringBuilder();
        for (int i = 0; i < Math.min(ciphertext.length(), 50); i++) {
            char c = ciphertext.charAt(i);
            charAnalysis.append(String.format("pos%d:'%c'(%d) ", i, c, (int)c));
        }
        result.put("charAnalysis", charAnalysis.toString());
        
        // 清理后的文本
        String cleaned = ciphertext.trim()
            .replaceAll("\\s+", "")
            .replaceAll("[^A-Za-z0-9+/=]", "");
        result.put("cleanedText", cleaned);
        result.put("cleanedLength", cleaned.length());
        result.put("isValidBase64", isValidBase64(cleaned));
        
        return result;
    }

    /**
     * 完整的SM2加密解密测试
     * 这个能成
     */
    @PostMapping("/testSm2Complete")
    public Map<String, Object> testSm2Complete(String plaintext) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 生成新的密钥对
            SM2 sm2 = SmUtil.sm2();
            String publicKey = sm2PublicKey;
            String privateKey = sm2PrivateKey;
            
            log.info("生成的公钥: {}", publicKey);
            log.info("生成的私钥: {}", privateKey);
            
            // 加密
            SM2 encryptSm2 = SmUtil.sm2(null, publicKey);
            String encrypted = encryptSm2.encryptBase64(plaintext, KeyType.PublicKey);
            String cleanedEncrypted = encrypted.replaceAll("\\s+", "");
            
            log.info("明文: {}", plaintext);
            log.info("加密后: {}", cleanedEncrypted);
            
            // 解密
            SM2 decryptSm2 = SmUtil.sm2(privateKey, null);
            String decrypted = decryptSm2.decryptStr(cleanedEncrypted, KeyType.PrivateKey);
            
            log.info("解密后: {}", decrypted);
            
            // 验证结果
            boolean success = plaintext.equals(decrypted);
            
            result.put("success", success);
            result.put("plaintext", plaintext);
            result.put("encrypted", cleanedEncrypted);
            result.put("decrypted", decrypted);
            result.put("publicKey", publicKey);
            result.put("privateKey", privateKey);
            result.put("message", success ? "加密解密成功" : "加密解密失败");
            
        } catch (Exception e) {
            log.error("测试失败: {}", e.getMessage());
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    //{
    //  "privateKey": "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgRjCl0TQVw4kuHDxxuhi7N/1y3s69LWHpmUAVOOppaNagCgYIKoEcz1UBgi2hRANCAARYQp6z24BvVnKclYFyHJFRCT1a1F5AHVXVUTLFIQ2K8c4LWp4hag0a2V6eU+QvLy2dTSE1wqi9TFumpNQrzvuy",
    //  "encrypted": "BIfisdG43cELL8wwOTfFUqE1tMdGtbJGQ7sJSSPLN1WUJe9WmCCgvGLQ0Envah9wXKceZYezEzhevzWtUoSStTz0nqkOb1cl/QEydEV/PqvVFNdAdfPzaonWqTwcatyNDfYv1KZhLRkfN6mgs9PlylQAT2SLjWk3trJvasLQ+fWA",
    //  "success": true,
    //  "plaintext": "6ed645ef0e1abea1bf1e4e935ff04f9e",
    //  "publicKey": "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEWEKes9uAb1ZynJWBchyRUQk9WtReQB1V1VEyxSENivHOC1qeIWoNGtlenlPkLy8tnU0hNcKovUxbpqTUK877sg==",
    //  "message": "加密解密成功",
    //  "decrypted": "6ed645ef0e1abea1bf1e4e935ff04f9e"
    //}

    /**
     * 测试添加注解的 方法
     */
    @PostMapping("/testAnnotation")
//    @ApiEncrypt(response = true)
    public void testAnnotation(@RequestBody String body) {
        System.out.println(body);
    }

    @PostMapping("/testKeys")
    public static String generateHexKey(String password) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hash = md.digest(password.getBytes(StandardCharsets.UTF_8));
        byte[] keyBytes = new byte[16]; // 取前16字节作为SM4密钥
        System.arraycopy(hash, 0, keyBytes, 0, keyBytes.length);
        return HexFormat.of().formatHex(keyBytes); // 转换为32位十六进制字符串
    }
    // 三十二进制sm4 秘钥 : 6ed645ef0e1abea1bf1e4e935ff04f9e
} 